package com.lanshiqin.webdemo.service.fix;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class BrochureFacadeFix {

    private ListeningExecutorService executorService;

    @Value("${brochureConvertExecutorPoolSize:2}")
    private int poolSize;

    @Value("${brochureConvertExecutorQueueSize:600}")
    private int queueSize;

    @Autowired
    private OfficeConvertServiceFix officeConvertServiceFix;

    @PostConstruct
    private void init(){
        executorService = MoreExecutors.listeningDecorator(
                new ThreadPoolExecutor(poolSize, poolSize
                        , 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueSize)
                        , new ThreadFactoryBuilder().setNameFormat("brochure-convert-executor-pool-%d").setDaemon(false).build()
                        , new ThreadPoolExecutor.AbortPolicy()));
    }

    public void asyncConvertBrochure(){
        // 线程池就两个线程，防止多线程并发时更加容易导致OOM
        try{
            executorService.submit(()-> {
                try {
                    convertBrochureFileToImgList();
                }finally {
                    System.out.println("finally 2");
                }
            });
        }catch (Exception e){
            e.printStackTrace();
//            log.warn("brochure convert threadPool task abort:{}",JSON.toJSONString(brochure));
        }
    }

    /**
     * 宣传册转为图片列表
     */
    private void convertBrochureFileToImgList(){

        Long startTime = System.currentTimeMillis();
        try{
            String pdfUrl = "file:///D:\\我的文档\\19mb的pdf文件.pdf";
//            String pdfUrl = "http://localhost:8080/Max_PDF_DEMO.pdf";
            String fileName = "19mb的pdf文件";
            // 假装用户的参数，这里真正开始核心的转换
            officeConvertServiceFix.pdfConvertToImg(pdfUrl,fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Long end = System.currentTimeMillis();
            System.out.println("convert done, time: " + (end-startTime)/1000);
        }

    }
}
